package cn.ac.iie.kgmanager.controller;

import cn.ac.iie.kgmanager.domain.Relation;
import cn.ac.iie.kgmanager.dto.request.Request;
import cn.ac.iie.kgmanager.dto.response.Response;
import cn.ac.iie.kgmanager.exception.ParamException;
import cn.ac.iie.kgmanager.service.RelationService;
import io.swagger.models.auth.In;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @ClassName RelationController
 * @Author tjh
 * @Date 19/6/12 上午10:04
 * @Version 1.0
 **/
@RestController
@AllArgsConstructor
@Slf4j
public class RelationController {

    private final RelationService relationService;


    // 批量新增关系
    @PostMapping("/relation")
    public Response addRelations(@RequestBody Request<Relation> request) {
        try {
            request.check();
            try {
                Set<String> ids = relationService.batchSaveRelations(request.getData());
                return Response.operateSucessAndHaveData(ids);
            } catch (Exception e) {
                log.error("批量新增关系错误:{}", e);
                return Response.databaseError("批量新增关系错误！");
            }
        } catch (ParamException pe) {
            return Response.paramError(pe.getMessage());
        }
    }

    // 批量删除关系
    @DeleteMapping("/relation/{ids}")
    public Response deleteRelations(@PathVariable(value = "ids") String[] ids) {

        if (ids == null || ids.length == 0) {
            return Response.paramError("要删除的id列表不能为空！");
        }
        try {
            int num = relationService.batchDeleteRelations(ids);
            return Response.operateSucessAndHaveData(num);
        } catch (Exception e) {
            log.error("批量删除关系失败:{}", e);
            return Response.databaseError("批量删除关系失败");
        }
    }

    // 批量修改关系
    @PutMapping("/relation/")
    public Response updateRelations(@RequestBody Request<Relation> request) {
        try {
            request.check();
            try {
                int num = relationService.batchUpdateRelations(request.getData());
                return Response.operateSucessAndHaveData(num);
            } catch (Exception e) {
                return Response.databaseError("批量修改关系错误！");
            }
        } catch (ParamException pe) {
            return Response.paramError(pe.getMessage());
        }
    }

    // 根据ID查询关系详情
    @GetMapping("/relation/{id}")
    public Response getRelationById(@PathVariable(value = "id") String id) {
        if (StringUtils.isBlank(id)) {
            return Response.paramError("id不能为空");
        }
        try {

            Relation relation = relationService.getRelationById(id);
            return Response.operateSucessAndHaveData(relation);
        } catch (Exception e) {
            return Response.databaseError("检索失败");
        }
    }

    // 根据两端实体查询关系
    @GetMapping("/node/relations")
    public Response getRelationByNode(@RequestParam(value = "source", required = false) String source,
                                      @RequestParam(value = "target", required = false) String target,
                                      @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                      @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                      @RequestParam(value = "depth", required = false) Integer depth) {

        if (StringUtils.isBlank(source) && StringUtils.isBlank(target)) {
            return Response.paramError("关系开始节点和关系结束节点必须有一个不为空！");
        }
        Relation relation = new Relation();
        relation.setStartId(source);
        relation.setEndId(target);

//        Integer finalPageNum = pageNum == null || pageNum == 0 ? 1 : pageNum;
//        Integer finalPageSize = pageSize == null || pageSize == 0 ? 10 : pageSize;
        Integer finalDepth = depth == null || depth <= 0 ? 1 : depth;


        AtomicInteger total = new AtomicInteger();
        AtomicReference<List<Relation>> relationList = new AtomicReference<List<Relation>>();

        Thread countThread = new Thread(() -> {
            total.set(relationService.countRelationByCondition(relation, finalDepth));
        });
        countThread.start();

        Thread findThread = new Thread(() -> {
            relationList.set(relationService.getRelationByCondition(relation, pageSize, pageNum, finalDepth));
        });
        findThread.start();

        try {
            countThread.join();
            findThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Response response = Response.operateSucessAndHaveData(relationList);
        response.setPageNum(pageNum);
        response.setSumCount(total.longValue());
        return response;

    }

    @GetMapping("/nodes/relations/{nodes}")
    public Response getRelationByNodes(@PathVariable(value = "nodes") String[] nodes) {
        if (nodes.length == 0) {
            return Response.operateSucessNoData();
        }
        try {
            List<Relation> relations = relationService.getRelationByNodes(nodes);
            return Response.operateSucessAndHaveData(relations);

        } catch (Exception e) {
            log.error("{}", e);
            return Response.databaseError("查询节点间关系错误！");
        }
    }
}
